//
//  YPHttpRequestMethod.m
//  AFGetText
//
//  Created by KiVen on 15/11/5.
//  Copyright © 2015年 张文权. All rights reserved.3
//

#import "YPHttpRequestMethod.h"
#import <Security/Security.h>
#import <Foundation/Foundation.h>
#import "MainTabbarViewController.h"

@implementation YPHttpRequestMethod


+(void)sendAsyRequestURL:(NSString *)url
                withData:(NSDictionary *)requestDictionary
     withCompletionBlock:(void (^)(NSDictionary *responseDictionary))aCompletionBlock
         withFailedBlock:(void (^)(NSError *error))aFailedBlock
           withIndicator:(BOOL)flag
                  atView:(UIView *)view;{
    

    if (flag == YES) {
        [MBProgressHUD showHUDAddedTo:view animated:YES];
    }
    
    AFHTTPSessionManager*manager=[[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kAppHostAddress]];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"application/json",@"text/html", nil];
    
    manager.requestSerializer.timeoutInterval = 10;
       NSLog(@"url:%@",url);
    
    
    NSString *encoded = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [manager GET:encoded parameters:requestDictionary success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        [YRProgressHUD hideHUDForView:view animated:YES];
        if (aCompletionBlock) {
            
            NSDictionary *responseDictionary =responseObject;
           
            
            if ([responseDictionary[@"status"] intValue]==1202) {
                
                if ([YPShareAccountInfo shareAccountInfo].token.length>0) {
                    
                    
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"CoreLockPWDKey"];
                    
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    [YPShareAccountInfo shareAccountInfo].g_password=nil;
                    
                    
                    [YPShareAccountInfo shareAccountInfo].token=nil;
                    
                    [[YPShareAccountInfo shareAccountInfo] saveData];
                    
                    YPLogonViewController*loginViewVC=[[YPLogonViewController alloc] init];
                    
                    BaseNavigationController*nav=[[BaseNavigationController alloc] initWithRootViewController:loginViewVC];
                    
                    UIWindow*window=[UIApplication sharedApplication].keyWindow;
                    
                    MainTabbarViewController*tabbar=(MainTabbarViewController*)window.rootViewController;
                    
                    [tabbar presentViewController:nav animated:YES completion:nil];
                    
                    
                    
                    
                    UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"你的账号已在其他设备登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    
                    [alert show];
                    
                }
                
            }
            
            
            
            
            aCompletionBlock(responseDictionary);
            
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        [YRProgressHUD hideHUDForView:view animated:YES];
        
        if (aFailedBlock != nil) {
            if (flag == YES) {
                
                
                [YRProgressHUD autoShowHUDAddedTo:view withText:@"网络错误,请检查网络"];
                
                [YRProgressHUD hideHUDForView:view animated:YES];
                
            }
            
            NSLog ( @"Error:%@" ,error);
            aFailedBlock(error);
            
        }

        
    }];
    

}



+(void)uploadImage:(UIImage *)image
                            parameters:(NSDictionary *)parameters
                                   url:(NSString *)url
                               success:(void(^)(NSDictionary *responseDictionary))success
                               failure:(void(^)(NSError *error))failure
                  uploadProgressBlock :(void(^) (NSInteger bytesWritten,long long totalBytesWritten, long long totalBytesExpectedToWrite))block atView:(UIView *)view;{
    
    [YRProgressHUD showHUDAddedTo:view animated:YES];
    
    
    
    
    AFHTTPSessionManager*manager=[[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kAppHostAddress]];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manager.requestSerializer.timeoutInterval = 10;

    
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        
        NSData * imageData = UIImagePNGRepresentation(image);
        
        [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"upfile.png" mimeType:@"image/png"];
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
         [YRProgressHUD hideHUDForView:view animated:YES];
        
        if ([responseObject[@"status"] intValue]==1202) {
            if ([YPShareAccountInfo shareAccountInfo].token.length>0) {
                
                
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"CoreLockPWDKey"];
                
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [YPShareAccountInfo shareAccountInfo].g_password=nil;
                
                
                [YPShareAccountInfo shareAccountInfo].token=nil;
                
                [[YPShareAccountInfo shareAccountInfo] saveData];
                
                YPLogonViewController*loginViewVC=[[YPLogonViewController alloc] init];
                
                BaseNavigationController*nav=[[BaseNavigationController alloc] initWithRootViewController:loginViewVC];
                
                UIWindow*window=[UIApplication sharedApplication].keyWindow;
                
                MainTabbarViewController*tabbar=(MainTabbarViewController*)window.rootViewController;
                
                [tabbar presentViewController:nav animated:YES completion:nil];
                
                
                
                
                UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"你的账号已在其他设备登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                
                [alert show];
                
            }
            
        }
        
        
        
        success(responseObject);

        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        [YRProgressHUD autoShowHUDAddedTo:view withText:@"网络错误,请检查网络"];
        
        [YRProgressHUD hideHUDForView:view animated:YES];
        
        NSLog(@"Failure %@",error.description);
        failure(error);

    }];
    
    
    
    
    
    
    
    
    
}


/**
 *  [manager POST:[urlString stringByAddingPercentEscapesUsingEncoding:4] parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
 
 if ([responseObject[@"status"] integerValue] != 0) {
 
 if ([responseObject[@"status"] integerValue] != 1202) {
 
 [SVProgressHUD showErrorWithStatus:responseObject[@"ret_msg"] duration:1];
 
 }else{
 
 [SVProgressHUD dismiss];
 }
 
 
 }
 
 successBlock(responseObject);
 
 } failure:^(NSURLSessionDataTask *task, NSError *error) {
 
 failBlock(error);
 }]
 */


+(void)updateRequestURL:(NSString *)url withData:(NSDictionary *)requestDictionary withCompletionBlock:(void (^)(NSDictionary *responseDictionary))aCompletionBlock withFailedBlock:(void (^)(NSError *error))aFailedBlock withIndicator:(BOOL)flag atView:(UIView *)view{
    
    if (flag == YES) {
        [MBProgressHUD showHUDAddedTo:view animated:YES];
    }
    
    AFHTTPSessionManager*manager=[[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kAppHostAddress]];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"application/json",@"text/html", nil];
    
    manager.requestSerializer.timeoutInterval = 10;
    NSLog(@"url:%@",url);
    
    
    [manager POST:[url stringByAddingPercentEscapesUsingEncoding:4] parameters:requestDictionary success:^(NSURLSessionDataTask *task, id responseObject) {
        
        [YRProgressHUD hideHUDForView:view animated:YES];
        
        if ([responseObject[@"status"] intValue]==1202) {
            if ([YPShareAccountInfo shareAccountInfo].token.length>0) {
                
                
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"CoreLockPWDKey"];
                
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [YPShareAccountInfo shareAccountInfo].g_password=nil;
                
                
                [YPShareAccountInfo shareAccountInfo].token=nil;
                
                [[YPShareAccountInfo shareAccountInfo] saveData];
                
                YPLogonViewController*loginViewVC=[[YPLogonViewController alloc] init];
                
                BaseNavigationController*nav=[[BaseNavigationController alloc] initWithRootViewController:loginViewVC];
                
                UIWindow*window=[UIApplication sharedApplication].keyWindow;
                
                MainTabbarViewController*tabbar=(MainTabbarViewController*)window.rootViewController;
                
                [tabbar presentViewController:nav animated:YES completion:nil];
                
                
                
                
                UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"你的账号已在其他设备登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                
                [alert show];
                
            }
            
        }
        
     aCompletionBlock(responseObject);

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [YRProgressHUD autoShowHUDAddedTo:view withText:@"网络错误,请检查网络"];
        
        [YRProgressHUD hideHUDForView:view animated:YES];

        aFailedBlock(error);
    }];

}

@end
